package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.QueryObject.StrategyQuery;
import cn.wolfcode.luowowo.domain.*;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.respository.*;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional  暂时不管事务
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyRespository strategyrRespository;
    @Autowired
    private StrategyCommentRespository strategyCommentRespository;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;
    @Autowired
    private IStrategyThemeService strategyThemeService;
    @Autowired
    private IDestinationService destinationService;


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public Strategy get(String id) {
        Optional<Strategy> optional = strategyrRespository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Strategy> list() {
        return strategyrRespository.findAll();
    }

    @Override
    //Page对象里面包括 : 总页数 每页显示条数
    //使用mongoTemplate 只能返回Page 需要把list封装成 page对象再返回
    public Page<Strategy> query(StrategyQuery qo) {
        Query query = new Query();
        //高级查询 根据目的地id
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if (StringUtils.hasLength(qo.getThemeId())) {
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }
        return DBHelper.query(mongoTemplate, Strategy.class, query, qo.getPageable());
    }

    @Override
    public void saveOrUpdate(Strategy strategy) {

        //1.根据id获取攻略分类的名字
        StrategyCatalog catalog = strategyCatalogService.get(strategy.getCatalogId());
        strategy.setCatalogName(catalog.getName());

        //2.在攻略分类对象中获取目的地的id和名字
        strategy.setDestId(catalog.getDestId());
        strategy.setDestName(catalog.getDestName());

        //3.根据id获取攻略主题的名字
        StrategyTheme theme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(theme.getName());

        //4.是否国外
        List<Destination> toast = destinationService.getToast(strategy.getDestId());
        if (toast != null && toast.size() > 0) {
            if ("中国".equals(toast.get(0).getName())) {
                strategy.setIsabroad(Strategy.ABROAD_NO);
            } else {
                strategy.setIsabroad(Strategy.ABROAD_YES);
            }
        }

        if (!StringUtils.hasLength(strategy.getId())) {
            //添加创建时间
            strategy.setCreateTime(new Date());
            //添加
            strategy.setId(null);
            strategyrRespository.save(strategy);
        } else {
            //更新
            //方案一: 1.查询 2.替代 3.save
            //方案二:
            //条件
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(strategy.getId()));
            //更新的列
            DBHelper.update(mongoTemplate, query, strategy,
                    "destId", "destName", "themeId", "themeName", "catalogId",
                    "catalogName", "title", "subTitle", "summary", "coverUrl",
                    "isabroad", "state", "content");

            /*
            Strategy newStrategy = new Strategy();
            //根据id查询出数据库中的对象
            Optional<Strategy> op = strategyrRespository.findById(strategy.getId());
            if (op.isPresent()) {
                newStrategy = op.get();
                strategy.setCreateTime(newStrategy.getCreateTime());
                //使用工具类进行拷贝 左边复制给右边
                BeanUtils.copyProperties(strategy, newStrategy);
                strategyrRespository.save(newStrategy);
            }*/
        }
    }

    @Override
    public void delete(String id) {
        strategyrRespository.deleteById(id);
    }

    @Override
    public List<Strategy> getStrategyByCatalogId(String CatalogId) {

        return strategyrRespository.findByCatalogId(CatalogId);
    }

    @Override
    public void changeState(int state, String id) {
        Optional<Strategy> optional = strategyrRespository.findById(id);
        if (optional.isPresent()) {
            Strategy strategy = optional.get();
            strategy.setState(state);
        }
    }

    @Override
    public List<Strategy> getHighViewNumStrategy(String destId) {
        PageRequest of = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Strategy> strategies = strategyrRespository.findByDestId(destId, of);
        return strategies;
    }

    @Override
    public List<Strategy> getByDestName(String destName) {
        return strategyrRespository.findByDestName(destName);
    }

}
